 package com.xuanzheng.company.servlet;

  import com.google.gson.Gson;
  import com.google.gson.JsonObject;
  import com.google.gson.JsonParser;
  import com.xuanzheng.company.entity.User;
  import com.xuanzheng.company.service.AIService;
  import com.xuanzheng.company.service.impl.AIServiceImpl;

  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.util.HashMap;
  import java.util.Map;

  @WebServlet("/aiChat")
  public class AIChatServlet extends HttpServlet {

      private final AIService aiService = new AIServiceImpl();
      private final Gson gson = new Gson();

      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {

          request.setCharacterEncoding("UTF-8");
          response.setContentType("application/json;charset=UTF-8");

          PrintWriter out = response.getWriter();

          try {
              // 获取用户信息
              HttpSession session = request.getSession(false);
              if (session == null) {
                  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                  out.print("{\"success\":false,\"message\":\"请先登录\"}");
                  return;
              }

              User user = (User) session.getAttribute("user");
              if (user == null) {
                  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                  out.print("{\"success\":false,\"message\":\"请先登录\"}");
                  return;
              }

              // 读取请求体
              StringBuilder jsonBuilder = new StringBuilder();
              BufferedReader reader = request.getReader();
              String line;
              while ((line = reader.readLine()) != null) {
                  jsonBuilder.append(line);
              }

              // 解析请求
              JsonObject requestJson = JsonParser.parseString(jsonBuilder.toString()).getAsJsonObject();
              String question = requestJson.has("message") ? requestJson.get("message").getAsString() : 
                               requestJson.has("question") ? requestJson.get("question").getAsString() : null;
              String modelId = requestJson.has("modelId") ? requestJson.get("modelId").getAsString() : null;
              
              if (question == null || question.trim().isEmpty()) {
                  Map<String, Object> errorResult = new HashMap<>();
                  errorResult.put("success", false);
                  errorResult.put("message", "问题内容不能为空");
                  out.print(gson.toJson(errorResult));
                  return;
              }

              // 调用AI服务，传递模型ID
              Map<String, Object> result;
              if (modelId != null && !modelId.trim().isEmpty()) {
                  result = aiService.sendChatRequest(user.getId(), question, modelId);
              } else {
                  result = aiService.sendChatRequest(user.getId(), question);
              }

              // 返回结果
              out.print(gson.toJson(result));

          } catch (Exception e) {
              e.printStackTrace();
              Map<String, Object> errorResult = new HashMap<>();
              errorResult.put("success", false);
              errorResult.put("message", "服务器内部错误");
              out.print(gson.toJson(errorResult));
          }

          out.flush();
          out.close();
      }
  }